local skin_files = { }

minetest.register_privilege("changeskin", "Jogador pode mudar sua propria skin.")

--###############################################################################################

lunoskins.setSkinHumanoid = function(player, skinname, grep)
	if player~=nil and player:is_player() then --Caso de erro!!!
		local name = player:get_player_name()
		if skinname~=nil and type(skinname)=="string" and skinname~="" then
			if grep==nil or grep=="" then  --Deve ser obrigatorio um grep. (Ja tentei criar uma funcaosem grep, mas nao funfa por causa do comando 'ls')
				grep = "skin_" 
			end

			local url = minetest.get_modpath("lunoskins").."/models/"..grep..tostring(skinname)..".png"
			--print("################################# [lunoskins.setSkinHumanoid("..player:get_player_name()..", "..skinname..", "..grep..")] url = "..url)
			local handler = io.open(url, 'r')
			if handler~=nil then
				minetest.log("action",name.." vestiu a skin '"..skinname.."'.")
				minetest.chat_send_player(name, "Voce esta vestindo a skin '"..tostring(skinname).."'.")
				player:set_properties({
					visual = "mesh",
					textures = {grep..skinname..".png"},
					--textures = {"character.png", },
					visual_size = {x=1, y=1},
					animation_speed = 30,
					animations = {
						-- Standard animations.
						stand     = { x=  0, y= 79, },
						lay       = { x=162, y=166, },
						walk      = { x=168, y=187, },
						mine      = { x=189, y=198, },
						walk_mine = { x=200, y=219, },
						-- Extra animations (not currently used by the game).
						sit       = { x= 81, y=160, },
					},
				})
				--[[
				minetest.after(1, function() -- <--So tocar som depois q o jogador logar completamente (Sem isso o servidor trava quando um novo jogador entrar)
					minetest.sound_play("disguise", {pos=player:getpos(), max_hear_distance = 7}) --toca som "disguise".ogg a distancia de 7 blocos do usuario.
				end)
				]]--
			else
				minetest.chat_send_player(name, "[lunoskins.setSkinHumanoid] A skin '"..tostring(skinname).."' nao existe!")
			end
		else
			minetest.log("erro","[lunoskins.setSkinHumanoid] ERRO CRITICO: O valor de parametro 'skinname' nao declarado!")
		end
	else
		--print("[lunoskins.setSkinHumanoid] ERRO CRITICO: O valor de parametro 'player' nao ser do tipo apropriado!")
		minetest.log("erro","[lunoskins.setSkinHumanoid] ERRO CRITICO: O valor de parametro 'player' nao ser do tipo apropriado!")
	end
end

lunoskins.getSkinDefault = function()
	return "padrao_sam" --skin_padrao_sam.png
end

lunoskins.doSkinDefault = function(player)
	lunoskins.setSkinHumanoid(player, lunoskins.getSkinDefault())
end

lunoskins.doUpdateSkin = function(player)
	if player~=nil and player:is_player() then --Caso de erro!!!
		local skinname = lunomods.getCharValue(player:get_player_name(), "skinname")
		--print("############################################### [lunoskins.doUpdateSkin("..player:get_player_name()..")] skinname = "..tostring(skinname))
		if skinname~=nil and skinname~="" then
			lunoskins.setSkinHumanoid(player, skinname)
		--elseif minetest.get_player_privs(player:get_player_name())["server"] then
		--	lunoskins.setSkinHumanoid(player, "trader")
		else
			lunoskins.doSkinDefault(player)
		end
	end
end

lunoskins.showSkinMod = function(name, pasta, grep)
	if grep==nil or grep=="" then  --Deve ser obrigatorio um grep. (Ja tentei criar uma funcaosem grep, mas nao funfa por causa do comando 'ls')
		grep = "skin_" 
	end
	skin_files = lunomods.readdir(pasta, "*.png", grep)
	minetest.chat_send_player(name, "", false)
	minetest.chat_send_player(name, "########## Listando skins ("..pasta..")... ##########", false)
	if #skin_files >=1 then
		for i, newskin in ipairs(skin_files) do 
			newskin = string.gsub(newskin, grep, "")
			newskin = string.gsub(newskin, ".png", "")
			minetest.chat_send_player(name, i.." --> "..newskin, false)
		end
	end
end

--[[
minetest.register_on_respawnplayer(function(player)
	if player~=nil and player:is_player() then --Caso de erro!!!
		local name = player:get_player_name()
		lunomods.setCharValue(name, "skinname", nil)
		lunoskins.doSkinDefault(player)
		--lunoskins.doUpdateSkin(player)
	end
end)
]]--

minetest.register_on_joinplayer(function(player)
	if player~=nil and player:is_player() then --Caso de erro!!!
		lunoskins.doUpdateSkin(player)
	end
end)


minetest.register_chatcommand("setskin", {
	params = "<skin> [<Jogador>]",
	description = "Define skin de um jogador.",
	privs = {server=true},
	func = function(name, param)
	
		--local new_ownername, sx, sy, sz, ex, ey, ez = string.match(param, "(.-) (.-)")
		local skinname, name_alvo = string.match(param, "([%a%d_]+) (.+)")
		local alvo = nil
		if name_alvo~=nil and name_alvo~="" then
			alvo = minetest.get_player_by_name(name_alvo)
		else
			alvo = minetest.get_player_by_name(name)
		end
		
		if alvo~=nil and alvo:is_player() then
			if skinname==nil and skinname=="default" then
				--/setskin default Stately
				lunomods.setCharValue(alvo:get_player_name(), "skinname", nil)
				--lunoskins.doSkinDefault(alvo)
				lunoskins.doUpdateSkin(alvo)
			elseif skinname~=nil and skinname~="" then
				lunomods.setCharValue(alvo:get_player_name(), "skinname", skinname)
				--lunoskins.setSkinHumanoid(alvo, skinname)
				lunoskins.doUpdateSkin(alvo)
			else
				minetest.chat_send_player(name, "[ERRO] SINTAXE: /setskin <skinname> [<Jogador>]")
			end
		else
			minetest.chat_send_player(name, "[ERRO] Jogador '"..name_alvo.."' nao encontrado!")
		end
		return true -- Handled chat message
	end,
})

minetest.register_chatcommand("skins", {
	params = "",
	description = "Exibe todas as skins disponiveis",
	privs = {changeskin=true},
	func = function(name, param)
		lunoskins.showSkinMod(name, minetest.get_modpath("lunoskins").."/models/")
		minetest.chat_send_player(name, "########## (precione F10 e use a rolagem do mouse para ler nomes de skins!!!) ##########", false)
		return true
	end,
})

minetest.register_chatcommand("myskin", {
	params = "<SkinName>",
	description = "poe uma skin para se mesmo.",
	privs = {changeskin=true},
	func = function(name, param)
		local player = minetest.get_player_by_name(name)
		if player~=nil and player:is_player() then --Caso de erro!!!
			if param~=nil and param~="" then --Caso de erro!!!
				lunomods.setCharValue(name, "skinname", param)
				lunoskins.doUpdateSkin(player)
				return true
			end
		end
	end,
})


